<template>
  <el-dialog
    ref="isPopWindows"
    v-dialogDrag
    title="提示"
    :visible.sync="isViewPopWindows"
    width="70%"
    :append-to-body="true"
    :close-on-click-modal="false"
    center
    @close="close"
    @opened="open"
  >
    <dialogHeader
      slot="title"
      :title="dynamicTextMap[popupsState]"
      :style-type="$store.state.app.dialogType"
    />
    <div class="formBoxContain">
      <!--
            buttons: 按钮
            froms: 表单
            fromsField: 表单对应的字段
            tableOption: 网格项
            dynamicApiConfigs: 取值
         -->
      <one-table-template
        ref="multipleTable"
        :dynamic-buttons="tableButtons"
        :dynamic-components="tableComponents"
        :dynamic-api-config="apiConfig"
        :dynamic-form-fields="formField"
        :dynamic-is-show-select="false"
        :dynamic-is-init-table="true"
        :dynamic-api-style="'restful'"
      />
    </div>
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import { formMixins } from '@/components/mixins/formMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/paSparePartsManagement'

export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  // 组件混入对象
  mixins: [formMixins],
  props: {
    // 是否关闭弹窗
    isViewPopWindows: {
      type: Boolean,
      default: false
    },
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      isViewPopWindows: false,
      // 保存API配置对象
      // apiConfig: orgApis.proConfigButtonMutationSave,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'button1',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: () => { this.save() },
          text: this.$t('sys.button.save'),
          position: 'right'
        },
        {
          compKey: 'button2',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => { this.close() },
          text: this.$t('sys.button.cancel'),
          position: 'right'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '运输方式编码：',
              codeField: 'transportModeCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: false,
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '运输方式名称：',
              codeField: 'transportModeName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey3',
              labelName: '运输限制：',
              codeField: 'isLimit',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '是' },
                { statusId: '0', statusText: '否' }
              ],
              type: 'dropdownList',
              isMul: false,
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey4',
              labelName: '状态：',
              codeField: 'isEnable',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '启用' },
                { statusId: '0', statusText: '停用' }
              ],
              type: 'dropdownList',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey5',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            }
          ],
      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(this, {
        transportModeCode: '',
        transportModeName: '',
        isLimit: '',
        isEnable: '',
        remark: '',
        transportModeId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },
  mounted() {
    this.tableComponents[0].disabled = this.popupsState === 'edit';
  },
  methods: {
    /**
     * @description 关闭弹窗
     * @time 2021、01、22
     */
    close() {
      this.$emit('close')
      this.emptyFormField()
      this.resetIconv()
      this.tableComponents[0].disabled = false
    },
    resetIconv() {
      this.$nextTick(() => {
        for (const attr in this.$refs['multipleTable'].$refs) {
          if (attr.startsWith('true')) {
            this.$refs['multipleTable'].$refs[attr][0].$children[0].$children[2].iconV = ''
          }
        }
      })
    },
    open() {
      this.toWatch()
      this.resetIconv()
      if (this.popupsState === 'edit') {
        this.tableComponents[0].disabled = true
      } else {
        console.log('open' + this.popupsState)
        // this.tableComponents.find(o => o['isLimit'])
        this.formField.isLimit = '0'
        this.formField.isEnable = '1'
      }
    },
    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpage')
      if (this.valid) {
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },

    // 编辑保存
    editSave() {
      console.log(this.formField)
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.transportEditSave,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: this.$t('sys.tips.esTip5') /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.isViewPopWindows = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message:
              '保存失败:' + response.msg,
            type: 'warn',
            uration: 1000
          })
        }
        this.isViewPopWindows = false
      })
    },

    // 新增保存
    addSave() {
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.transportEditAdd,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1000
          })
          this.isViewPopWindows = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message:
              '添加失败:' + response.msg,
            type: 'warn',
            uration: 1000
          })
        }
        this.isViewPopWindows = false
      })
    }
  }
}
</script>
<style scoped>
.formBoxContain {
  /* height: 150px; */
  padding: 20px 5px;
}
</style>
